﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.Diagnostics;
using System.IO;
using Microsoft.AspNetCore.DataProtection;
using System.Net.Sockets;
namespace UtilsBase
{
    public class UtilsDecrypt
    {
        public static string keyAdd = "yihong";
        private static string sKey = "yihong";
        

        public static string GenerateHmacSha256(string data, string key)
        {
            using (HMACSHA256 hmac = new HMACSHA256(Encoding.UTF8.GetBytes(key)))
            {
                byte[] textBytes = Encoding.UTF8.GetBytes(data);
                byte[] hashBytes = hmac.ComputeHash(textBytes);
                return BitConverter.ToString(hashBytes).Replace("-", "").ToLowerInvariant();
            }

            //key = key ?? "";
            //var encoding = new System.Text.ASCIIEncoding();
            //byte[] keyByte = encoding.GetBytes(key);
            //byte[] messageBytes = encoding.GetBytes(data);
            //using (var hmacsha256 = new HMACSHA256(keyByte))
            //{
            //    byte[] hashmessage = hmacsha256.ComputeHash(messageBytes);

            //    string hashresult = BitConverter.ToString(hashmessage).Replace("-", "").ToLowerInvariant();
            //    return hashresult;
            //}
        }

        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="value"></param>
        /// <param name="key"></param>
        /// <param name="Iv"></param>
        /// <returns></returns>
        public static string DESDecrypt(string value, string key, string Iv)
        {
            string str;
            byte[] destinationArray = new byte[8];
            Array.Copy(Encoding.UTF8.GetBytes(key.PadRight(destinationArray.Length)), destinationArray, destinationArray.Length);
            byte[] buffer2 = new byte[8];
            Array.Copy(Encoding.UTF8.GetBytes(Iv.PadRight(buffer2.Length)), buffer2, buffer2.Length);
            ICryptoTransform transform = new DESCryptoServiceProvider().CreateDecryptor(destinationArray, buffer2);
            byte[] buffer = Convert.FromBase64String(value);
            MemoryStream stream = new MemoryStream();
            try
            {
                using (CryptoStream stream2 = new CryptoStream(stream, transform, CryptoStreamMode.Write))
                {
                    stream2.Write(buffer, 0, buffer.Length);
                }
                str = Encoding.UTF8.GetString(stream.ToArray());
            }
            catch (CryptographicException)
            {
                throw new CryptographicException("Unable to decrypt data, >>key or inintialization vector maybe invalid!");
            }
            return str;
        }
        /// <summary>
        /// 加密,注意去掉
        /// </summary>
        /// <param name="value"></param>
        /// <param name="key"></param>
        /// <param name="Iv"></param>
        /// <returns></returns>
        public static string DESEncrypt(string value, string key, string Iv)
        {
            string str;
            byte[] destinationArray = new byte[8];
            Array.Copy(Encoding.UTF8.GetBytes(key.PadRight(destinationArray.Length)), destinationArray, destinationArray.Length);
            byte[] buffer2 = new byte[8];
            Array.Copy(Encoding.UTF8.GetBytes(Iv.PadRight(buffer2.Length)), buffer2, buffer2.Length);
            ICryptoTransform transform = new DESCryptoServiceProvider().CreateEncryptor(destinationArray, buffer2);
            byte[] bytes = Encoding.UTF8.GetBytes(value);
            MemoryStream stream = new MemoryStream();
            try
            {
                using (CryptoStream stream2 = new CryptoStream(stream, transform, CryptoStreamMode.Write))
                {
                    stream2.Write(bytes, 0, bytes.Length);
                }
                str = Convert.ToBase64String(stream.ToArray());
            }
            catch (CryptographicException)
            {
                throw new CryptographicException("Unable to encrypt data, >> key or inintialization vector maybe invalid!");
            }
            return str;
        }


        public static string MD5Encrypt(string str)
        {
            byte[] bytes = Encoding.Default.GetBytes(str);
            bytes = new MD5CryptoServiceProvider().ComputeHash(bytes);
            string str2 = "";
            for (int i = 0; i < bytes.Length; i++)
            {
                str2 = str2 + bytes[i].ToString("x").PadLeft(2, '0');
            }
            return str2;
        }

        public static string MD5aspToc(string str)
        {

            using (var md5 = MD5.Create())
            {
                var result = md5.ComputeHash(Encoding.UTF8.GetBytes(str));
                var strResult = BitConverter.ToString(result);
                return strResult.Replace("-", "").ToLower();
            }
        }
        public static string MD5aspToc2(string strPwd)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] data = Encoding.Default.GetBytes(strPwd);//将字符编码为一个字节序列 
            byte[] md5data = md5.ComputeHash(data);//计算data字节数组的哈希值 
            md5.Clear();
            string str = "";
            for (int i = 0; i < md5data.Length - 1; i++)
            {
                str += md5data[i].ToString("x").PadLeft(2, '0');
            }
            return str;
        }
        public static string GetMD5Hash(string ConvertString)
        {
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            string t2 = BitConverter.ToString(md5.ComputeHash(Encoding.Default.GetBytes(ConvertString)), 4, 8);
            t2 = t2.Replace("-", "").ToString();
            return t2.Substring(0, 16);
            //MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            //string t2 = BitConverter.ToString(md5.ComputeHash(UTF8Encoding.Default.GetBytes(ConvertString)), 4, 8);
            //t2 = t2.Replace("-", "");

            //t2 = t2.ToLower();

            //return t2;
        }

        /// <summary>
        /// DES解密方法
        /// </summary>
        /// <param name="valueString"></param>
        /// <returns></returns>
        public static string DecryptString(string valueString)
        {
            if (valueString != "")
            {
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                byte[] inputByteArray = new byte[valueString.Length / 2];
                for (int x = 0; x < valueString.Length / 2; x++)
                {
                    int i = Convert.ToInt32(valueString.Substring(x * 2, 2), 0x10);
                    inputByteArray[x] = (byte)i;
                }
                des.Key = Encoding.ASCII.GetBytes(sKey);
                des.IV = Encoding.ASCII.GetBytes(sKey);
                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                cs.Close();
                cs.DisposeAsync();
                des.Clear();
                des.Dispose();
                // StringBuilder ret = new StringBuilder();
                string result= Encoding.Default.GetString(ms.ToArray());
                ms.Close();
                ms.DisposeAsync();
                return result;
            }
            return "";
        }
        /// <summary>
        /// DES加密方法
        /// </summary>
        /// <param name="valueString"></param>
        /// <returns></returns>
        public static string EncryptString(string valueString)
        {
            if (valueString != "")
            {
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                byte[] inputByteArray = Encoding.Default.GetBytes(valueString);
                des.Key = Encoding.ASCII.GetBytes(sKey);
                des.IV = Encoding.ASCII.GetBytes(sKey);
                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                StringBuilder ret = new StringBuilder();
                foreach (byte b in ms.ToArray())
                {
                    ret.AppendFormat("{0:X2}", b);
                }
                //ret.ToString();

                cs.Close();
                cs.DisposeAsync();
                ms.Close();
                ms.DisposeAsync();
                des.Clear();
                des.Dispose();
                return ret.ToString();
            }
            return null;
        }

        public static string DecryptDES(string decryptString)
        {
            try
            {
                byte[] bytes = Encoding.UTF8.GetBytes(sKey);
                byte[] rgbIV = Encoding.UTF8.GetBytes(sKey);
                byte[] buffer = Convert.FromBase64String(decryptString);
                DESCryptoServiceProvider cryptoServiceProvider = new DESCryptoServiceProvider();
                MemoryStream memoryStream = new MemoryStream();
                CryptoStream cryptoStream = new CryptoStream(memoryStream, cryptoServiceProvider.CreateDecryptor(bytes, rgbIV), CryptoStreamMode.Write);
                cryptoStream.Write(buffer, 0, buffer.Length);
                cryptoStream.FlushFinalBlock();
                return Encoding.UTF8.GetString(memoryStream.ToArray());
            }
            catch
            {
                return decryptString;
            }
        }



        #region 字符串加密



        /// <summary>
        /// 多重加密
        /// </summary>
        /// <param name="pwd">需要加密的字符串</param>
        /// <param name="type">type 类型，16位还是32位，16位就是取32位的第8到16位</param>
        /// <returns>密文</returns>
        public string Encrypt_Multiple(string pwd)
        {
            string result = SHA384Encrypt(pwd);
            result = SHA1_Encrypt(result);
            result = DoMd5Encode(result, "16");
            return result;
        }


        /// <summary>
        /// 对字符串进行ＭＤ5加密，不区分大小写的
        /// </summary>
        /// <param name="pwd">需要加密的字符串</param>
        /// <param name="type">type 类型，16位还是32位，16位就是取32位的第8到16位</param>
        /// <returns>密文</returns>
        public static string DoMd5Encode(string pwd, string type)
        {
            byte[] result = Encoding.Default.GetBytes(pwd + keyAdd);
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            byte[] output = md5.ComputeHash(result);
            md5.Clear();
            md5.Dispose();
            if (type == "16")
                return BitConverter.ToString(output).Replace("-", "").ToLower().Substring(8, 16);
            else
                return BitConverter.ToString(output).Replace("-", "").ToLower();

        }
        /// <summary>
        /// 对字符串进行SHA1加密
        /// </summary>
        /// <param name="strIN">需要加密的字符串</param>
        /// <returns>密文</returns>
        public static string SHA1_Encrypt(string Text)
        {
            byte[] StrRes = Encoding.Default.GetBytes(Text);
            HashAlgorithm iSHA = new SHA1CryptoServiceProvider();
            StrRes = iSHA.ComputeHash(StrRes);
            StringBuilder EnText = new StringBuilder();
            foreach (byte iByte in StrRes)
            {
                EnText.AppendFormat("{0:x2}", iByte);
            }
            return EnText.ToString();
        }
        /// <summary>
        /// SHA256加密，不可逆转
        /// </summary>
        /// <param name="str">string str:被加密的字符串</param>
        /// <returns>返回加密后的字符串</returns>
        private static string SHA256Encrypt(string Text)
        {
            SHA256 s256 = new SHA256Managed();
            byte[] byte1;
            byte1 = s256.ComputeHash(Encoding.Default.GetBytes(Text));
            s256.Clear();
            return Convert.ToBase64String(byte1);
        }
        /// <summary>
        /// SHA384加密，不可逆转
        /// </summary>
        /// <param name="str">string str:被加密的字符串</param>
        /// <returns>返回加密后的字符串</returns>
        private static string SHA384Encrypt(string Text)
        {
            SHA384 s384 = new SHA384Managed();
            byte[] byte1;
            byte1 = s384.ComputeHash(Encoding.Default.GetBytes(Text));
            s384.Clear();
            return Convert.ToBase64String(byte1);
        }
        /// <summary>
        /// SHA512加密，不可逆转
        /// </summary>
        /// <param name="str">string str:被加密的字符串</param>
        /// <returns>返回加密后的字符串</returns>
        private static string SHA512Encrypt(string Text)
        {
            SHA512 s512 = new SHA512Managed();
            byte[] byte1;
            byte1 = s512.ComputeHash(Encoding.Default.GetBytes(Text));
            s512.Clear();
            return Convert.ToBase64String(byte1);
        }
        //默认密钥向量
        private static byte[] Keys = { 0xEF, 0xAB, 0x56, 0x78, 0x90, 0x34, 0xCD, 0x12 };
        /// <summary>
        /// DES加密字符串
        /// </summary>
        /// <param name="encryptString">待加密的字符串</param>
        /// <param name="encryptKey">加密密钥,要求为8位</param>
        /// <returns>加密成功返回加密后的字符串，失败返回源串</returns>
        public static string EncryptDES(string encryptString, string encryptKey)
        {
            try
            {
                byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8));
                byte[] rgbIV = Keys;
                byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
                DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();
                MemoryStream mStream = new MemoryStream();
                CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
                cStream.Write(inputByteArray, 0, inputByteArray.Length);
                cStream.FlushFinalBlock();
                return Convert.ToBase64String(mStream.ToArray());
            }
            catch
            {
                return encryptString;
            }
        }
        /// <summary>
        /// DES解密字符串
        /// </summary>
        /// <param name="decryptString">待解密的字符串</param>
        /// <param name="decryptKey">解密密钥,要求为8位,和加密密钥相同</param>
        /// <returns>解密成功返回解密后的字符串，失败返源串</returns>
        public static string DecryptDES(string decryptString, string decryptKey)
        {
            try
            {
                byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey.Substring(0, 8));
                byte[] rgbIV = Keys;
                byte[] inputByteArray = Convert.FromBase64String(decryptString);
                DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider();
                MemoryStream mStream = new MemoryStream();
                CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
                cStream.Write(inputByteArray, 0, inputByteArray.Length);
                cStream.FlushFinalBlock();
                return Encoding.UTF8.GetString(mStream.ToArray());
            }
            catch
            {
                return decryptString;
            }
        }
        #endregion

    }
}
